package document.controller;


import document.dao.DocumentDao;
import document.entity.Document;
import org.json.JSONObject;
import utils.FileUploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

@WebServlet(value = "/document/upload")
public class DocumentUploadServlet extends HttpServlet {
    private final DocumentDao documentDao = new DocumentDao();
    private static final long serialVersionUID = 1;

    public DocumentUploadServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        doPost(request, response);
    }

    /**
     * 上传文档表单信息
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        System.out.println("进入了DocumentUploadServlet");

        response.setContentType("text/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/x-www-form-urlencoded");

        Document document = new Document();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        FileUploadUtil.uploadFile(request);
        document.setId(Integer.parseInt((String) request.getAttribute("id")));
        document.setProject_id(Integer.parseInt((String) request.getAttribute("projectId")));
//        document.setProjectName(request.getParameter("projectName"));
        document.setFileType((String) request.getAttribute("fileType"));
        document.setFileName((String) request.getAttribute("fileName"));
        document.setUploadTime(ft.format(new Date()));
        document.setUploadPerson((String) request.getAttribute("uploadPerson"));
        document.setUploadPath((String) request.getAttribute("file_url"));

        System.out.println(document);

        boolean res = documentDao.addDocument(document);

        JSONObject jsonObject = new JSONObject();
        if(res) {
            jsonObject.put("code",0);
            jsonObject.put("message","文档上传成功");
        } else {
            jsonObject.put("code",500);
            jsonObject.put("message","文档上传失败");
        }
        System.out.println(jsonObject.toString());
        response.getWriter().write(jsonObject.toString());
//        response.getWriter().close();
    }
}
